package com.bs.regsystemapi.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bs.regsystemapi.entity.Duty;
import com.bs.regsystemapi.entity.PatPerson;
import com.bs.regsystemapi.entity.PatRegRecord;
import com.bs.regsystemapi.entity.PatientEntity;
import com.bs.regsystemapi.modal.dto.patregrecord.*;
import com.bs.regsystemapi.service.*;
import com.bs.regsystemapi.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author ning
 * @Date 2023/2/14 18:51
 */
@RestController
@RequestMapping("/patRegRecord")
@Api(tags = {"挂号记录api接口"})
@Slf4j
public class PatRegRecordController {

    @Autowired
    private PatRegRecordService patRegRecordService;
    @Autowired
    private PatPersonService patPersonService;
    @Autowired
    private UserService doctorService;
    @Autowired
    private PatPayRecordService patPayRecordService;
    @Autowired
    private DutyService dutyService;

    @ApiOperation(value = "根据医生no查挂号记录")
    @RequestMapping(value = "/getPatRegRecordByDoctorNo", method = RequestMethod.POST)
    public ResponseResult getPatRegRecordByDoctorNo(@RequestBody @Validated PatRegRecordListForm form) throws Exception {
        if (StringUtils.isEmpty(form.getVisitDate())) {
            form.setVisitDate(DateUtil.toString(new Date(), "yyyy-MM-dd"));
        }
        ManagePageResult patRegRecordList = patRegRecordService.getPatRegRecordByDoctorNo(form);
        return ResponseResult.ok().put(patRegRecordList);
    }

    @ApiOperation(value = "查未就诊挂号记录")
    @RequestMapping(value = "/getRegInfo", method = RequestMethod.POST)
    public ResponseResult getPatRegRecordByDoctorNo(@RequestBody QueryRegInfoForm form) {
        ManagePageResult regInfo = patRegRecordService.getRegInfo(form);
        return ResponseResult.ok().put(regInfo);
    }

    @ApiOperation(value = "查历史挂号记录")
    @RequestMapping(value = "/getHisRegInfo", method = RequestMethod.POST)
    public ResponseResult getHisPatRegRecordByDoctorNo(@RequestBody QueryRegInfoForm form) {
        ManagePageResult regInfo = patRegRecordService.getHisRegInfo(form);
        return ResponseResult.ok().put(regInfo);
    }

    @ApiOperation(value = "根据患者No查挂号记录")
    @RequestMapping(value = "/getPatRegRecordByPatNo", method = RequestMethod.GET)
    public ResponseResult getPatRegRecordByRegNo() {
        String patNo;
        try {
            // 获取patNo
            patNo = (String) StpUtil.getLoginIdByToken((String) ThreadLocalUtils.get("Authorization"));
            log.info("用户号:" + patNo);
        } catch (NullPointerException e) {
            return ResponseResult.error("请求头参数Authorization为空!");
        }
        return ResponseResult.ok().put(patRegRecordService.getPatRegRecordByRegNo(patNo));
    }

    @ApiOperation(value = "根据医生名字或预约日期或科室查挂号记录")
    @RequestMapping(value = "/getPatRegRecordByOther", method = RequestMethod.GET)
    public ResponseResult getPatRegRecordByOther(PatRegRecordRequestForm form) throws Exception {
        return ResponseResult.ok().put(patRegRecordService.getPatRegRecordByOther(form));
    }

    @ApiOperation(value = "根据预约状态和患者no获取预约记录")
    @RequestMapping(value = "/getPatRegRecordByRegStateAndPatNo", method = RequestMethod.GET)
    public ResponseResult getPatRegRecordByRegStateAndPatNo(@RequestParam(value = "regState", required = false) String regState) {
        String patNo = "";
        try {
            // 获取patNo
            patNo = (String) StpUtil.getLoginIdByToken((String) ThreadLocalUtils.get("Authorization"));
            log.info("用户号:" + patNo);
        } catch (NullPointerException e) {
            return ResponseResult.error("请求头参数Authorization为空!");
        }
        return ResponseResult.ok().put(patRegRecordService.getPatRegRecordByRegStateAndPatNo(regState,patNo));
    }

    @ApiOperation(value = "预约详情")
    @RequestMapping(value = "/getPatRegRecordDetail", method = RequestMethod.GET)
    public ResponseResult getPatRegRecordDetail(@RequestParam("regNo") String regNo) {
        return ResponseResult.ok().put(patRegRecordService.getPatRegRecordDetail(regNo));
    }

    @ApiOperation(value = "新增挂号", notes = "后端方法待修复")
    @RequestMapping(value = "/savePatRegRecord", method = RequestMethod.POST)
    public ResponseResult savePatRegRecord(@RequestBody @Validated AddPatRegRecordForm form) {
        List<PatRegRecord> patRegRecord = patRegRecordService.getBaseMapper().selectList(
                new QueryWrapper<PatRegRecord>()
                        .eq("doctor_no", form.getDoctorNo())
                        .eq("person_no", form.getPersonNo())
                        .eq("is_delete", "1")
                        .eq("visit_time", form.getVisitTime())
                        .eq("visit_data", form.getVisitData())
        );
        // 查询到该时间段已经已预约该医生
        if (!patRegRecord.isEmpty()) {
            return ResponseResult.error("查询到该时间段已经已预约该医生");
        }
        String regNo = patRegRecordService.savePatRegRecord(form);

        return ResponseResult.ok().put("regNo",regNo);
    }


    @ApiOperation(value = "取消挂号")
    @RequestMapping(value = "/cancelPatRegRecord", method = RequestMethod.POST)
    public ResponseResult cancelPatRegRecord(@RequestBody @Validated CancelPatRegRecordForm form) {
        UpdateWrapper<PatRegRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("reg_no",form.getRegNo());
        updateWrapper.set("reg_state","2");
        boolean flag = patRegRecordService.update(updateWrapper);
        if (!flag) {
            return ResponseResult.error("取消挂号记录失败!");
        }

        return ResponseResult.ok("取消成功");
    }


    @ApiOperation(value = "删除挂号")
    @RequestMapping(value = "/deletePatRegRecord", method = RequestMethod.POST)
    public ResponseResult deletePatRegRecord(@RequestBody @Validated CancelPatRegRecordForm form) {
        UpdateWrapper<PatRegRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("reg_no",form.getRegNo());
        updateWrapper.set("is_delete","0");
        boolean flag = patRegRecordService.update(updateWrapper);
        if (!flag) {
            return ResponseResult.error("删除挂号记录失败!");
        }
        return ResponseResult.ok("删除成功");
    }

    @ApiOperation(value = "患者新增挂号")
    @RequestMapping(value = "/appReg/{doctorNo}", method = RequestMethod.POST)
    public ResponseResult appReg(HttpServletRequest request, @PathVariable String doctorNo, @RequestBody @Validated AppRegRecord form) throws Exception {
        String patNo = "";
        Cookie[] cookies = request.getCookies();
        if (cookies.length > 0){
            for (Cookie cookie : cookies) {
                if ("appPatient".equals(cookie.getName())){
                    patNo = cookie.getValue();
                }
            }
        }
        LambdaQueryWrapper<PatPerson>  lbw = new LambdaQueryWrapper<>();
        lbw.eq(PatPerson::getPatNo,patNo);
        PatPerson patPerson = patPersonService.getOne(lbw);
        if (null == patPerson){
            return ResponseResult.error("该用户没有就诊卡!");
        }

        //入参日期转换为data
        Date visitData = DateUtil.toDate(form.getPublishTime(), "yyyy-MM-dd");

        List<PatRegRecord> patRegRecord = patRegRecordService.getBaseMapper().selectList(
                new QueryWrapper<PatRegRecord>()
                        .eq("doctor_no", doctorNo)
                        .eq("person_no", patPerson.getPersonNo())
                        .eq("is_delete", "1")
                        .eq("visit_time", form.getVisitTime())
                        .eq("visit_data", visitData)
        );
        // 查询到该时间段已经已预约该医生
        if (!patRegRecord.isEmpty()) {
            return ResponseResult.error("查询到该时间段已经已预约该医生");
        }

        //挂号操作
        AddPatRegRecordForm patForm = new AddPatRegRecordForm();
        patForm.setPersonNo(patPerson.getPersonNo());
        patForm.setDoctorNo(doctorNo);
        patForm.setVisitTime(form.getVisitTime());
        patForm.setVisitData(visitData);
        patForm.setIllnessDetail(form.getDetail());
        patForm.setPersonRemark(form.getRemark());
        String regNo = patRegRecordService.savePatRegRecord(patForm);

        patPayRecordService.savePay(patNo,patPerson.getPersonNo(),doctorNo,regNo);
        return ResponseResult.ok().put("regNo",regNo);
    }


}
